package com.cy.store.service.impl;

import com.cy.store.entity.User;
import com.cy.store.mapper.UserMapper;
import com.cy.store.service.IUserService;
import com.cy.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

@Service  //将当前类的对象交给spring管理，可以自动创建对象和进行对象的维护
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void register(User user) {
        User temp = userMapper.findByUsername(user.getUsername());
        if (temp != null){
            throw new UserNameDuplicatedException("用户名被占用！");
        }
        user.setIsDelete(0);
        user.setCreatedUser(user.getUsername());
        user.setModifiedUser(user.getUsername());
        Date date = new Date();
        user.setCreatedTime(date);
        user.setModifiedTime(date);
        //密码加密处理:md5算法
        // 串 + 密码 + 串  --> md5处理,连续加密三次
        // 盐值 + 密码 + 盐值   -->盐值就是一个随机的字符串
        String oldPassword = user.getPassword();
        //随机生成一个盐值
        String salt = UUID.randomUUID().toString().toUpperCase();
        //记录下此刻的盐值
        user.setSalt(salt);
        //将密码和盐值一起加密处理
        String newPassword = getMD5Password(oldPassword, salt);
        user.setPassword(newPassword);
        Integer result = userMapper.insert(user);
        if (result != 1){
            throw new InsertException("在用户注册过程中产生了未知的异常!");
        }
    }

    @Override
    public User login(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user == null){
            throw new UserNotFoundException("用户数据不存在!");
        }
        String passwordInMysql = user.getPassword();
        String salt = user.getSalt();
        String MD5Password = getMD5Password(password,salt);
        if (!(passwordInMysql.equals(MD5Password))){
            throw new PasswordNotMatchException("用户密码错误!");
        }
        if (user.getIsDelete() == 1){
            throw new UserNotFoundException("用户数据不存在!");
        }
        //压缩数据，提升系统性能
        User result = new User();
        result.setUid(user.getUid());
        result.setUsername(user.getUsername());
        result.setAvatar(user.getAvatar());
        return result;
    }

    @Override
    public void changePassword(Integer uid, String username, String oldPassword, String newPassword) {
        User user = userMapper.findByUid(uid);
        if (user == null || user.getIsDelete() ==1){
            throw new UserNotFoundException("用户数据不存在！");
        }
        String oldMD5Password = getMD5Password(oldPassword,user.getSalt());
        if (!(user.getPassword().equals(oldMD5Password))){
            throw new PasswordNotMatchException("密码错误！");
        }
        String newMD5Password = getMD5Password(newPassword,user.getSalt());
        Integer result = userMapper.updatePasswordByUid(uid, newMD5Password, username, new Date());
        if (result != 1){
            throw new UpdateException("更新数据产生未知的异常！");
        }
    }

    @Override
    public User getUserInfoByUid(Integer uid) {
        User user = userMapper.findByUid(uid);
        if (user == null || user.getIsDelete() ==1){
            throw new UserNotFoundException("用户数据不存在！");
        }
        User result = new User();
        result.setUsername(user.getUsername());;
        result.setPhone(user.getPhone());
        result.setEmail(user.getEmail());
        result.setGender(user.getGender());
        return result;
    }

    @Override
    public void changeInfo(Integer uid, String username, User user) {
        User result = userMapper.findByUid(uid);
        if (result == null || result.getIsDelete() ==1){
            throw new UserNotFoundException("用户数据不存在！");
        }
        user.setUid(uid);
        user.setModifiedUser(username);
        user.setModifiedTime(new Date());
        Integer row = userMapper.updateInfoByUid(user);
        if (row != 1){
            throw new UpdateException("更新数据时出现未知异常！");
        }
    }

    @Override
    public void changeAvatar(Integer uid, String avatar, String username) {
        User result = userMapper.findByUid(uid);
        if (result == null || result.getIsDelete() ==1){
            throw new UserNotFoundException("用户数据不存在！");
        }
        Integer row = userMapper.updateAvatarByUid(uid, avatar, username, new Date());
        if (row != 1){
            throw new UpdateException("更新头像时产生未知异常！");
        }
    }


    /**
     * md5加密处理
     * @param password
     * @param salt
     * @return
     */
    private String getMD5Password(String password,String salt){
        //md5加密算法方法调用(进行三次加密)
        for (int i = 0; i < 3; i++) {
            password = DigestUtils.md5DigestAsHex(((salt) + password + (salt)).getBytes()).toUpperCase();
        }
        return password;
    }
}
